package com.example.administrator.jim.imuisample.messages;


import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.text.format.DateFormat;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.example.administrator.jim.BaseActivity;
import com.example.administrator.jim.MainActivity;
import com.example.administrator.jim.R;
import com.example.administrator.jim.addresslist.UserInfoDescActivity;
import com.example.administrator.jim.bean.UserInfoBean;
import com.example.administrator.jim.imuisample.models.DefaultUser;
import com.example.administrator.jim.imuisample.models.MyMessage;
import com.example.administrator.jim.imuisample.views.ChatView;
import com.example.administrator.jim.utils.CameraUtils;
import com.example.administrator.jim.utils.UriUtils;
import com.example.administrator.jim.value.MyValue;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.jiguang.imui.chatinput.ChatInputView;
import cn.jiguang.imui.chatinput.listener.OnCameraCallbackListener;
import cn.jiguang.imui.chatinput.listener.OnClickEditTextListener;
import cn.jiguang.imui.chatinput.listener.OnMenuClickListener;
import cn.jiguang.imui.chatinput.listener.RecordVoiceListener;
import cn.jiguang.imui.chatinput.model.FileItem;
import cn.jiguang.imui.commons.ImageLoader;
import cn.jiguang.imui.commons.models.IMessage;
import cn.jiguang.imui.messages.MsgListAdapter;
import cn.jiguang.imui.messages.ViewHolderController;
import cn.jiguang.imui.messages.ptr.PtrHandler;
import cn.jiguang.imui.messages.ptr.PullToRefreshLayout;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.DownloadCompletionCallback;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.content.CustomContent;
import cn.jpush.im.android.api.content.EventNotificationContent;
import cn.jpush.im.android.api.content.ImageContent;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.content.VoiceContent;
import cn.jpush.im.android.api.event.MessageEvent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static cn.jpush.im.android.api.JMessageClient.FLAG_NOTIFY_DEFAULT;
import static cn.jpush.im.android.api.JMessageClient.FLAG_NOTIFY_DISABLE;


public class MessageListActivity extends BaseActivity implements View.OnTouchListener,
        EasyPermissions.PermissionCallbacks, SensorEventListener {

    private final static String TAG = "MessageListActivity";
    private final int RC_RECORD_VOICE = 0x0001;
    private final int RC_CAMERA = 0x0002;
    private final int RC_PHOTO = 0x0003;
    private ChatView mChatView;
    private MsgListAdapter<MyMessage> mAdapter;
    private List<MyMessage> mData;
    private String mFriendName="";
    private InputMethodManager mImm;
    private Window mWindow;
    private HeadsetDetectReceiver mReceiver;
    private SensorManager mSensorManager;
    private Sensor mSensor;
    private Bitmap mFriendBitmap,mMyBitmap;
    private PowerManager mPowerManager;
    private PowerManager.WakeLock mWakeLock;
    private MyMessage mMessage_Receive;
    private String mFrientsuername;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_activity);
        getSupportActionBar().hide();
        setClazz(MessageListActivity.class);
        this.mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mWindow = getWindow();
        registerProximitySensorListener();
        initUserdatas();
        mChatView = (ChatView) findViewById(R.id.chat_view);
        mChatView.initModule();
        initMsgAdapter();
        mReceiver = new HeadsetDetectReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
        registerReceiver(mReceiver, intentFilter);
        mChatView.setOnTouchListener(this);
        mChatView.setMenuClickListener(new OnMenuClickListener() {
            @Override
            public boolean onSendTextMessage(final CharSequence input) {
                if (input.length() == 0) {
                    return false;
                }
                Message singleTextMessage = JMessageClient.createSingleTextMessage(mFrientsuername, null, input.toString());
                final MyMessage message = new MyMessage(input.toString(), IMessage.MessageType.SEND_TEXT.ordinal());
                message.setUserInfo(new DefaultUser("1", mFriendName, mMyBitmap));
                message.setTimeString(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()));
                message.setMessageStatus(IMessage.MessageStatus.SEND_GOING);
                mAdapter.addToStart(message, true);
                singleTextMessage.setOnSendCompleteCallback(new BasicCallback() {
                    @Override
                    public void gotResult(int i, String s) {
                        if(i==0){
                            message.setMessageStatus(IMessage.MessageStatus.SEND_SUCCEED);
                        }else {
                            message.setMessageStatus(IMessage.MessageStatus.SEND_FAILED);
                        }
                        mAdapter.updateMessage(message);
                    }
                });
                JMessageClient.sendMessage(singleTextMessage);
                return true;
            }

            @Override
            public void onSendFiles(List<FileItem> list) {
                if (list == null || list.isEmpty()) {
                    return;
                }
                for (final FileItem item : list) {
                    if (item.getType() == FileItem.Type.Image) {
                        Message ImageMessage = null;
                        try {
                            final MyMessage message = new MyMessage(null, IMessage.MessageType.SEND_IMAGE.ordinal());
                            message.setMediaFilePath(item.getFilePath());
                            message.setUserInfo(new DefaultUser("1", mFriendName, mMyBitmap));
                            message.setMessageStatus(IMessage.MessageStatus.SEND_GOING);
                            message.setTimeString(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()));
                            MessageListActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mAdapter.addToStart(message, true);
                                }
                            });
                            ImageMessage = JMessageClient.createSingleImageMessage(mFrientsuername, new File(item.getFilePath()));
                            ImageMessage.setOnSendCompleteCallback(new BasicCallback() {
                                @Override
                                public void gotResult(int i, String s) {
                                    if(i==0){
                                        message.setMessageStatus(IMessage.MessageStatus.SEND_SUCCEED);
                                    }else {
                                        message.setMessageStatus(IMessage.MessageStatus.SEND_FAILED);
                                    }
                                    mAdapter.updateMessage(message);
                                }
                            });
                            JMessageClient.sendMessage(ImageMessage);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }

//                    } else if (item.getType() == FileItem.Type.Video) {
//                        final MyMessage  message = new MyMessage(null, IMessage.MessageType.SEND_VIDEO.ordinal());
//                        message.setDuration(((VideoItem) item).getDuration());
//                        MessageListActivity.this.runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                mAdapter.addToStart(message, true);
//                            }
//                        });
                    } else {
                        throw new RuntimeException("Invalid FileItem type. Must be Type.Image or Type.Video");
                    }
                }
            }

            @Override
            public boolean switchToMicrophoneMode() {
                scrollToBottom();
                String[] perms = new String[]{
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                };

                if (!EasyPermissions.hasPermissions(MessageListActivity.this, perms)) {
                    EasyPermissions.requestPermissions(MessageListActivity.this,
                            getResources().getString(R.string.rationale_record_voice),
                            RC_RECORD_VOICE, perms);
                }
                return true;
            }

            @Override
            public boolean switchToGalleryMode() {
                scrollToBottom();
                String[] perms = new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE
                };

                if (!EasyPermissions.hasPermissions(MessageListActivity.this, perms)) {
                    EasyPermissions.requestPermissions(MessageListActivity.this,
                            getResources().getString(R.string.rationale_photo),
                            RC_PHOTO, perms);
                }
                return true;
            }

            @Override
            public boolean switchToCameraMode() {
                scrollToBottom();
                String[] perms = new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO
                };

                if (!EasyPermissions.hasPermissions(MessageListActivity.this, perms)) {
                    EasyPermissions.requestPermissions(MessageListActivity.this,
                            getResources().getString(R.string.rationale_camera),
                            RC_CAMERA, perms);
                } else {

                }
                return false;
            }

            @Override
            public boolean switchToEmojiMode() {
                scrollToBottom();
                return true;
            }
        });

        mChatView.setRecordVoiceListener(new RecordVoiceListener() {
            @Override
            public void onStartRecord() {
                // set voice file path, after recording, audio file will save here
                String path = Environment.getExternalStorageDirectory().getPath() + "/voice";
                File destDir = new File(path);
                if (!destDir.exists()) {
                    destDir.mkdirs();
                }
                mChatView.setRecordVoiceFile(destDir.getPath(), DateFormat.format("yyyy-MM-dd-hhmmss",
                        Calendar.getInstance(Locale.CHINA)) + "");
            }

            @Override
            public void onFinishRecord(File voiceFile, int duration) {
                final MyMessage message = new MyMessage(null, IMessage.MessageType.SEND_VOICE.ordinal());
                message.setUserInfo(new DefaultUser("1", mFriendName, mMyBitmap));
                message.setMediaFilePath(voiceFile.getPath());
                message.setDuration(duration);
                message.setMessageStatus(IMessage.MessageStatus.SEND_GOING);
                message.setTimeString(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()));
                mAdapter.addToStart(message, true);
                try {
                    Message singleVoiceMessage = JMessageClient.createSingleVoiceMessage(mFrientsuername,"", voiceFile, duration);
                    singleVoiceMessage.setOnSendCompleteCallback(new BasicCallback() {
                        @Override
                        public void gotResult(int i, String s) {
                            if(i==0){
                                message.setMessageStatus(IMessage.MessageStatus.SEND_SUCCEED);
                            }else {
                                message.setMessageStatus(IMessage.MessageStatus.SEND_FAILED);
                            }
                            mAdapter.updateMessage(message);
                        }
                    });
                    JMessageClient.sendMessage(singleVoiceMessage);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onCancelRecord() {

            }
        });

        mChatView.setOnCameraCallbackListener(new OnCameraCallbackListener() {
            @Override
            public void onTakePictureCompleted(final String photoPath) {
                //暂时消除拍照
                Message ImageMessage = null;
                try {
                    final MyMessage message = new MyMessage(null, IMessage.MessageType.SEND_IMAGE.ordinal());
                    message.setMediaFilePath(photoPath);
                    message.setMessageStatus(IMessage.MessageStatus.SEND_GOING);
                    message.setUserInfo(new DefaultUser("1", mFriendName, mMyBitmap));
                    message.setTimeString(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()));
                    MessageListActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAdapter.addToStart(message, true);
                        }
                    });
                    ImageMessage = JMessageClient.createSingleImageMessage(mFrientsuername, new File(photoPath));
                    ImageMessage.setOnSendCompleteCallback(new BasicCallback() {
                        @Override
                        public void gotResult(int i, String s) {
                            if(i==0){
                                message.setMessageStatus(IMessage.MessageStatus.SEND_SUCCEED);
                            }else {
                                message.setMessageStatus(IMessage.MessageStatus.SEND_FAILED);
                            }
                            mAdapter.updateMessage(message);
                        }
                    });
                    JMessageClient.sendMessage(ImageMessage);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStartVideoRecord() {

            }

            @Override
            public void onFinishVideoRecord(String videoPath) {

            }

            @Override
            public void onCancelVideoRecord() {

            }
        });

        mChatView.setOnTouchEditTextListener(new OnClickEditTextListener() {
            @Override
            public void onTouchEditText() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mChatView.getMessageListView().smoothScrollToPosition(0);
                    }
                }, 100);

            }
        });

        mChatView.getSelectAlbumBtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到图片选择器
                Matisse.from(MessageListActivity.this)
                        .choose(MimeType.allOf()) // 选择 mime 的类型
                        .countable(true)
                        .maxSelectable(9) // 图片选择的最多数量
                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f) // 缩略图的比例
                        .theme(R.style.Matisse_Zhihu)
                        .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                        .forResult(CameraUtils.PHOTO_REQUEST_GALLERY); // 设置作为标记的请求码
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CameraUtils.PHOTO_REQUEST_GALLERY) {
            if (data != null) {
                List<Uri> uris = Matisse.obtainResult(data);
                for (Uri path:uris){
                    String filePathFromContentUri = UriUtils.getFilePathFromContentUri(path, getContentResolver());
                    Message ImageMessage = null;
                    try {
                        final MyMessage message = new MyMessage(null, IMessage.MessageType.SEND_IMAGE.ordinal());
                        message.setMediaFilePath(filePathFromContentUri);
                        message.setMessageStatus(IMessage.MessageStatus.SEND_GOING);
                        message.setUserInfo(new DefaultUser("1", mFriendName, mMyBitmap));
                        message.setTimeString(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()));
                        MessageListActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mAdapter.addToStart(message, true);
                            }
                        });
                        ImageMessage = JMessageClient.createSingleImageMessage(mFrientsuername, new File(filePathFromContentUri));
                        ImageMessage.setOnSendCompleteCallback(new BasicCallback() {
                            @Override
                            public void gotResult(int i, String s) {
                                if(i==0){
                                    message.setMessageStatus(IMessage.MessageStatus.SEND_SUCCEED);
                                }else {
                                    message.setMessageStatus(IMessage.MessageStatus.SEND_FAILED);
                                }
                                mAdapter.updateMessage(message);
                            }
                        });
                        JMessageClient.sendMessage(ImageMessage);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    //加载用户头像和信息
    private void initUserdatas() {
        mFrientsuername = getIntent().getStringExtra("username");
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(final ObservableEmitter<Integer> e) throws Exception {
                JMessageClient.getUserInfo(mFrientsuername, new GetUserInfoCallback() {
                    @Override
                    public void gotResult(int i, String s, UserInfo userInfo) {
                        if(i==0){
                            if(userInfo.getNickname().equals("")){
                                mFriendName= mFrientsuername;
                            }else {
                                mFriendName=userInfo.getNickname();
                            }
                            mChatView.setTitle(mFriendName);
                            userInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
                                @Override
                                public void gotResult(int i, String s, Bitmap bitmap) {
                                    mFriendBitmap=bitmap;
                                    e.onNext(i);
                                }
                            });
                        }
                    }
                });
            }
        }).subscribeOn(Schedulers.io())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        initMyUserinfo();
                    }
                });
    }
    //加载自的头像
    private void initMyUserinfo() {
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(final ObservableEmitter<Integer> e) throws Exception {
                MainActivity.mMyInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
                    @Override
                    public void gotResult(int i, String s, Bitmap bitmap) {
                        mMyBitmap=bitmap;
                        e.onNext(i);
                    }
                });
            }
        }).subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        //添加历史消息
                        mData = getMessages();
                        mAdapter.addToEnd(mData);
                    }
                });
    }
    private void registerProximitySensorListener() {
        try {
            mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
            mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
            mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
            mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
            mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        try {
            if (audioManager.isBluetoothA2dpOn() || audioManager.isWiredHeadsetOn()) {
                return;
            }
            if (mAdapter.getMediaPlayer().isPlaying()) {
                float distance = event.values[0];
                if (distance >= mSensor.getMaximumRange()) {
                    mAdapter.setAudioPlayByEarPhone(0);
                    setScreenOn();
                } else {
                    mAdapter.setAudioPlayByEarPhone(2);
                    ViewHolderController.getInstance().replayVoice();
                    setScreenOff();
                }
            } else {
                if (mWakeLock != null && mWakeLock.isHeld()) {
                    mWakeLock.release();
                    mWakeLock = null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void setScreenOn() {
        if (mWakeLock != null) {
            mWakeLock.setReferenceCounted(false);
            mWakeLock.release();
            mWakeLock = null;
        }
    }

    private void setScreenOff() {
        if (mWakeLock == null) {
            mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
        }
        mWakeLock.acquire();
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    private class HeadsetDetectReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
                if (intent.hasExtra("state")) {
                    int state = intent.getIntExtra("state", 0);
                    mAdapter.setAudioPlayByEarPhone(state);
                }
            }
        }
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }
    //获取历史消息
    private List<MyMessage> getMessages() {
        final List<MyMessage> list = new ArrayList<>();
        Conversation singleConversation = JMessageClient.getSingleConversation(mFrientsuername);
        if(singleConversation!=null){
            List<Message> allMessage = singleConversation.getAllMessage();
            IMessage.MessageType messageType;
            MyMessage message;
            for(Message msg:allMessage){
                String userName = msg.getFromUser().getUserName();
                if(userName.equals(mFrientsuername)){
                    switch (msg.getContentType()){
                        case text:
                            message = new MyMessage(((TextContent) msg.getContent()).getText(), IMessage.MessageType.RECEIVE_TEXT.ordinal());
                            message.setUserInfo(new DefaultUser("0",  mFriendName, mFriendBitmap));
                            list.add(message);
                            break;
                        case image:
                            message = new MyMessage(null, IMessage.MessageType.RECEIVE_IMAGE.ordinal());
                            message.setMediaFilePath(((ImageContent) msg.getContent()).getLocalThumbnailPath());
                            message.setUserInfo(new DefaultUser("0",  mFriendName, mFriendBitmap));
                            list.add(message);
                            break;
                        case video:
                            messageType= IMessage.MessageType.RECEIVE_VIDEO;
                            break;
                        case voice:
                            final VoiceContent voiceContent = (VoiceContent) msg.getContent();
                            String localPath = voiceContent.getLocalPath();
                            if(localPath!=null&&!localPath.equals("")){
                                message = new MyMessage(null, IMessage.MessageType.RECEIVE_VOICE.ordinal());
                                message.setMediaFilePath(voiceContent.getLocalPath());
                                message.setDuration(voiceContent.getDuration());
                                message.setUserInfo(new DefaultUser("0",  mFriendName, mFriendBitmap));
                                list.add(message);
                            }else {
                                voiceContent.downloadVoiceFile(msg, new DownloadCompletionCallback() {
                                    @Override
                                    public void onComplete(int i, String s, File file) {
                                        if (i == 0) {
                                            MyMessage message = new MyMessage(null, IMessage.MessageType.RECEIVE_VOICE.ordinal());
                                            message.setUserInfo(new DefaultUser("0", mFriendName, mFriendBitmap));
                                            message.setMediaFilePath(file.getPath());
                                            message.setDuration(voiceContent.getDuration());
                                            list.add(message);
                                        }
                                    }
                                });
                            }
                            break;
                        case file:
                            messageType= IMessage.MessageType.RECEIVE_FILE;
                            break;
                    }
                }else {
                    switch (msg.getContentType()){
                        case text:
                            message = new MyMessage(((TextContent) msg.getContent()).getText(), IMessage.MessageType.SEND_TEXT.ordinal());
                            message.setUserInfo(new DefaultUser("1", mFriendName, mMyBitmap));
                            list.add(message);
                            break;
                        case image:
                            message = new MyMessage(null, IMessage.MessageType.SEND_IMAGE.ordinal());
                            message.setMediaFilePath(((ImageContent) msg.getContent()).getLocalThumbnailPath());
                            message.setUserInfo(new DefaultUser("1",  mFriendName, mMyBitmap));
                            list.add(message);
                            break;
                        case video:
                            messageType= IMessage.MessageType.SEND_VIDEO;
                            break;
                        case voice:
                            final VoiceContent voiceContent = (VoiceContent) msg.getContent();
                            String localPath = voiceContent.getLocalPath();
                            if(localPath!=null&&!localPath.equals("")){
                                message = new MyMessage(null, IMessage.MessageType.SEND_VOICE.ordinal());
                                message.setMediaFilePath(voiceContent.getLocalPath());
                                message.setDuration(voiceContent.getDuration());
                                message.setUserInfo(new DefaultUser("1",  mFriendName, mMyBitmap));
                                list.add(message);
                            }else {
                                voiceContent.downloadVoiceFile(msg, new DownloadCompletionCallback() {
                                    @Override
                                    public void onComplete(int i, String s, File file) {
                                        if (i == 0) {
                                            MyMessage message = new MyMessage(null, IMessage.MessageType.SEND_VOICE.ordinal());
                                            message.setUserInfo(new DefaultUser("1", mFriendName, mMyBitmap));
                                            message.setMediaFilePath(file.getPath());
                                            message.setDuration(voiceContent.getDuration());
                                            list.add(message);
                                        }
                                    }
                                });
                            }
                            break;
                        case file:
                            messageType= IMessage.MessageType.SEND_FILE;
                            break;
                    }
                }


            }
        }
//        message.setTimeString(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()));
        if(list.size()>0){
            Collections.reverse(list);
        }
        return list;
    }

    private void initMsgAdapter() {
        ImageLoader imageLoader = new ImageLoader() {
            @Override
            public void loadAvatarImage(ImageView avatarImageView, Bitmap bitmap) {
                // You can use other image load libraries.
                if(bitmap!=null){
                    avatarImageView.setImageBitmap(bitmap);
                }else {
                    avatarImageView.setImageResource(R.mipmap.aurora_headicon_default);
                }
            }

            @Override
            public void loadImage(ImageView imageView, String string) {
                // You can use other image load libraries.
                Glide.with(getApplicationContext())
                        .load(string)
                        .fitCenter()
                        .placeholder(R.drawable.aurora_picture_not_found)
                        .override(400, Target.SIZE_ORIGINAL)
                        .into(imageView);
            }
        };

        // Use default layout
        MsgListAdapter.HoldersConfig holdersConfig = new MsgListAdapter.HoldersConfig();
        mAdapter = new MsgListAdapter<>("0", holdersConfig, imageLoader);
        // If you want to customise your layout, try to create custom ViewHolder:
        // holdersConfig.setSenderTxtMsg(CustomViewHolder.class, layoutRes);
        // holdersConfig.setReceiverTxtMsg(CustomViewHolder.class, layoutRes);
        // CustomViewHolder must extends ViewHolders defined in MsgListAdapter.
        // Current ViewHolders are TxtViewHolder, VoiceViewHolder.

        mAdapter.setOnMsgClickListener(new MsgListAdapter.OnMsgClickListener<MyMessage>() {
            @Override
            public void onMessageClick(MyMessage message) {
                // do something
                if (message.getType() == IMessage.MessageType.RECEIVE_VIDEO.ordinal()
                        || message.getType() == IMessage.MessageType.SEND_VIDEO.ordinal()) {
                    //查看视频逻辑
//                    if (!TextUtils.isEmpty(message.getMediaFilePath())) {
//                        Intent intent = new Intent(MessageListActivity.this, VideoActivity.class);
//                        intent.putExtra(VideoActivity.VIDEO_PATH, message.getMediaFilePath());
//                        startActivity(intent);
//                    }
                } else if(message.getType() == IMessage.MessageType.RECEIVE_IMAGE.ordinal()
                        || message.getType() == IMessage.MessageType.SEND_IMAGE.ordinal()){
                    Intent intent = new Intent(MessageListActivity.this, ImageActivity.class);
                    intent.putExtra(MyValue.PHOTOFILEPATH,message.getMediaFilePath());
                    startActivity(intent);
                }
            }
        });

        mAdapter.setMsgLongClickListener(new MsgListAdapter.OnMsgLongClickListener<MyMessage>() {
            @Override
            public void onMessageLongClick(MyMessage message) {
                Toast.makeText(getApplicationContext(),
                        getApplicationContext().getString(R.string.message_long_click_hint),
                        Toast.LENGTH_SHORT).show();
            }
        });

        mAdapter.setOnAvatarClickListener(new MsgListAdapter.OnAvatarClickListener<MyMessage>() {
            @Override
            public void onAvatarClick(MyMessage message) {
                final DefaultUser muserInfo = (DefaultUser) message.getFromUser();
                final UserInfoBean mUserInfoBean=new UserInfoBean();
                JMessageClient.getUserInfo(mFrientsuername, new GetUserInfoCallback() {
                    @Override
                    public void gotResult(int i, String s, UserInfo userInfo) {
                        if(i==0){
                            if(muserInfo.getId().equals("0")){
                                mUserInfoBean.setNikkname(userInfo.getNickname());
                                mUserInfoBean.setBeizhu(userInfo.getNotename());
                                if(userInfo.getBirthday()>0){
                                    mUserInfoBean.setBirthdry(paseTime(userInfo.getBirthday()));
                                }else {
                                    mUserInfoBean.setBirthdry("");
                                }
                                mUserInfoBean.setUsername(userInfo.getUserName());
                                mUserInfoBean.setGexingqianm(userInfo.getSignature());
                                if(String.valueOf(userInfo.getGender()).equals("male")) {
                                    mUserInfoBean.setGender("男");
                                }else if(String.valueOf(userInfo.getGender()).equals("female")) {
                                    mUserInfoBean.setGender("女");
                                }else {
                                    mUserInfoBean.setGender("保密");
                                }
                                mUserInfoBean.setDiqu(userInfo.getAddress());
                            }else {
                                mUserInfoBean.setNikkname(MainActivity.mMyInfo.getNickname());
                                mUserInfoBean.setBeizhu(MainActivity.mMyInfo.getNotename());
                                if(userInfo.getBirthday()>0){
                                    mUserInfoBean.setBirthdry(paseTime(userInfo.getBirthday()));
                                }else {
                                    mUserInfoBean.setBirthdry("");
                                }
                                mUserInfoBean.setUsername(MainActivity.mMyInfo.getUserName());
                                mUserInfoBean.setGexingqianm(MainActivity.mMyInfo.getSignature());
                                if(String.valueOf(MainActivity.mMyInfo.getGender()).equals("male")) {
                                    mUserInfoBean.setGender("男");
                                }else if(String.valueOf(MainActivity.mMyInfo.getGender()).equals("female")) {
                                    mUserInfoBean.setGender("女");
                                }else {
                                    mUserInfoBean.setGender("保密");
                                }
                                mUserInfoBean.setDiqu(MainActivity.mMyInfo.getAddress());
                            }

                            Intent intent=new Intent(MessageListActivity.this,UserInfoDescActivity.class);
                            intent.putExtra("isfriend",userInfo.isFriend());
                            mUserInfoBean.setBitmap(null);
                            intent.putExtra("userinfo",mUserInfoBean);
                            startActivity(intent);
                        }
                    }
                });
            }
        });

        mAdapter.setMsgStatusViewClickListener(new MsgListAdapter.OnMsgStatusViewClickListener<MyMessage>() {
            @Override
            public void onStatusViewClick(MyMessage message) {
                // message status view click, resend or download here
            }
        });
        MyMessage eventMsg = new MyMessage("以上为历史消息", IMessage.MessageType.EVENT.ordinal());
        mAdapter.addToStart(eventMsg, true);
        PullToRefreshLayout layout = mChatView.getPtrLayout();
        layout.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PullToRefreshLayout layout) {
                loadNextPage();
            }
        });
        // Deprecated, should use onRefreshBegin to load next page
        mAdapter.setOnLoadMoreListener(new MsgListAdapter.OnLoadMoreListener() {
            @Override
            public void onLoadMore(int page, int totalCount) {
//                Log.i("MessageListActivity", "Loading next page");
//                loadNextPage();
            }
        });

        mChatView.setAdapter(mAdapter);
        mAdapter.getLayoutManager().scrollToPosition(0);
    }

    private void loadNextPage() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mAdapter.setLoadCount(mAdapter.getLoadCount()+20);
                mAdapter.notifyDataSetChanged();
                mChatView.getPtrLayout().refreshComplete();
            }
        }, 1000);
    }

    private void scrollToBottom() {
        mAdapter.getLayoutManager().scrollToPosition(0);
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                ChatInputView chatInputView = mChatView.getChatInputView();

                if (view.getId() == chatInputView.getInputView().getId()) {
                    scrollToBottom();
                    if (chatInputView.getMenuState() == View.VISIBLE
                            && !chatInputView.getSoftInputState()) {
                        chatInputView.dismissMenuAndResetSoftMode();
                        return false;
                    } else {
                        return false;
                    }
                }
                if (chatInputView.getMenuState() == View.VISIBLE) {
                    chatInputView.dismissMenuLayout();
                }
                try {
                    View v = getCurrentFocus();
                    if (mImm != null && v != null) {
                        mImm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                        mWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
                                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                        view.clearFocus();
                        chatInputView.setSoftInputState(false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case MotionEvent.ACTION_UP:
                view.performClick();
                break;
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
        mFrientsuername="";
        mSensorManager.unregisterListener(this);
    }

    //    =======================事件处理==============================
public void onEvent(MessageEvent event){
    final Message msg = event.getMessage();
    boolean isMessageFromThisUser = msg.getFromUser().getUserName().trim().equals(mFrientsuername.trim());
    if(isMessageFromThisUser){
        JMessageClient.setNotificationFlag(FLAG_NOTIFY_DISABLE);
        switch (msg.getContentType()){
            case text:
                //处理文字消息
                TextContent textContent = (TextContent) msg.getContent();
                mMessage_Receive = new MyMessage(textContent.getText(), IMessage.MessageType.RECEIVE_TEXT.ordinal());
                mMessage_Receive.setUserInfo(new DefaultUser("0", mFriendName, mFriendBitmap));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter.addToStart(mMessage_Receive, true);
                    }
                });
                break;
            case image:
                //处理图片消息
                ImageContent imageContent = (ImageContent) msg.getContent();
                mMessage_Receive = new MyMessage(null, IMessage.MessageType.RECEIVE_IMAGE.ordinal());
                mMessage_Receive.setMediaFilePath(imageContent.getLocalThumbnailPath());
                mMessage_Receive.setUserInfo(new DefaultUser("0",  mFriendName, mFriendBitmap));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter.addToStart(mMessage_Receive, true);
                    }
                });
                break;
            case voice:
                //处理语音消息
                final VoiceContent voiceContent = (VoiceContent) msg.getContent();
                voiceContent.downloadVoiceFile(msg, new DownloadCompletionCallback() {
                    @Override
                    public void onComplete(int i, String s, File file) {
                        if (i == 0) {
                            final MyMessage message = new MyMessage(null, IMessage.MessageType.RECEIVE_VOICE.ordinal());
                            message.setUserInfo(new DefaultUser("0", mFriendName, mFriendBitmap));
                            message.setMediaFilePath(file.getPath());
                            message.setDuration(voiceContent.getDuration());
                            message.setTimeString(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date()));
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mAdapter.addToStart(message, true);
                                }
                            });
                        }
                    }
                });
                break;
            case custom:
                //处理自定义消息
                CustomContent customContent = (CustomContent) msg.getContent();
                customContent.getNumberValue("custom_num"); //获取自定义的值
                customContent.getBooleanValue("custom_boolean");
                customContent.getStringValue("custom_string");
                break;
            case eventNotification:
                //处理事件提醒消息
                EventNotificationContent eventNotificationContent = (EventNotificationContent)msg.getContent();
                switch (eventNotificationContent.getEventNotificationType()){
                    case group_member_added:
                        //群成员加群事件
                        break;
                    case group_member_removed:
                        //群成员被踢事件
                        break;
                    case group_member_exit:
                        //群成员退群事件
                        break;
                    case group_info_updated://since 2.2.1
                        //群信息变更事件
                        break;
                }
                break;
        }
    }else {
        JMessageClient.setNotificationFlag(FLAG_NOTIFY_DEFAULT);
    }
    }
    //转换时间为年月日显示
    private String paseTime(long time) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date= new Date(time);
        return format.format(date);
    }
}
